package com.fingard.dsp.bank.directbank.tjcb01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.sql.Connection;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

public class TJCB01SinglePay extends TJCB01Base implements ISinglePay {
    private static final String INSERTRECEIPT = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,REQSEQID,BANKREQSEQID,TRANSDATE) values (?,?,?,?,?);";
    private static final String SELECTRECEIPT = "SELECT BANKREQSEQID,TRANSDATE FROM REQSEQIDMAPPING WHERE REQSEQID=? and BANKCODE=?;";

    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        if ("1".equals(p_req1908.singleDetail.sameBnk)) {
            //同行
            retAts = d_B2eTransferInBank(p_req1908, retAts);
        } else {
            //跨行
            retAts = B2eTransferOutBank(p_req1908, retAts);
        }
        return retAts;
    }

    //190801 B2eTransferInBank
    public RetAtsSingle d_B2eTransferInBank(ReqSingle p_req1908, RetAtsSingle retAts) throws Exception {
        RetAtsSglDetail tmpRetAtsDetail = new RetAtsSglDetail();
        Connection conn = null;
        try {
            TJCB01Header tjcb01Header = new TJCB01Header();
            tjcb01Header.transName = "B2eTransferInBank";
            tjcb01Header.clientTime = Format.DateTime2Format.format(new Date());
            tjcb01Header.batchID = p_req1908.reqHeader.transSeqID;
            tjcb01Header.transCount = "1";
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeader(xmlWriter, tjcb01Header);
            xmlWriter.writeStartElement("RequestBody");
            XElement requestRecord = new XElement("RequestRecord", "");
            requestRecord.addChild(new XElement("AcctNo", p_req1908.singleDetail.payAct));//付款账号
            requestRecord.addChild(new XElement("PayeeAcctNo", p_req1908.singleDetail.recAct));//收款账号
            requestRecord.addChild(new XElement("Amount", p_req1908.singleDetail.payAmount));//付款金额
            requestRecord.addChild(new XElement("Note", p_req1908.singleDetail.abstractATS));//存放对账码（明细查询时获取）

            String sendjnlno = DateHelper.convertDateTimetoD8(p_req1908.singleDetail.payDate) + bankFront.org + p_req1908.singleDetail.askNumber;
            requestRecord.addChild(new XElement("Sendjnlno", sendjnlno));
            nodeAnalysis(p_req1908.singleDetail.srcXElement, requestRecord, getCharset());
            xmlWriter.writeXElement(requestRecord);
            xmlWriter.writeEndDocument();

            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            boolean isSendToBank = true;
            try {
                conn = FGBiz.getLocalDbConn();
                int count = JDBCHelper.update(conn, INSERTRECEIPT, new Object[]{uuid, p_req1908.reqHeader.bankCode, p_req1908.singleDetail.askNumber, sendjnlno, DateHelper.convertDateTimetoD8(p_req1908.singleDetail.payDate)});
                if (count < 1) {
                    isSendToBank = false;
                }
            } catch (Exception e) {
                isSendToBank = false;
            } finally {
                if (conn != null) {
                    conn.close();
                }
                if (!isSendToBank) {
                    tmpRetAtsDetail.respCode = "0";
                    tmpRetAtsDetail.respInfo = "发送前流水号落库失败，未发送支付请求，请跟银行确认结果后手工处理";
                    tmpRetAtsDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                    retAts.writeRetDetail(tmpRetAtsDetail);
                    return retAts;
                }
            }


            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), p_req1908.reqHeader.transType, p_req1908.reqHeader.commandCode);

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRespCode = tmpBkReader.getFirstTextNotNull("/transaction/RespondHeader/respondCode");
                    String tmpRespMsg = tmpBkReader.getFirstTextNotNull("/transaction/RespondHeader/respondInfo");
                    tmpRetAtsDetail.respCode = "0";
                    tmpRetAtsDetail.respInfo = tmpRespMsg;
                    tmpRetAtsDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                    tmpRetAtsDetail.transState = tmpRespCode;
                    tmpRetAtsDetail.payInfoCode = tmpRespCode;
                } else {
                    tmpRetAtsDetail.respCode = "-1";
                    tmpRetAtsDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo("单笔同行转账异常，详情请查看DSP日志！");
            WriteBankLogLn("单笔同行转账异常:" + e.getMessage());
        }
        retAts.writeRetDetail(tmpRetAtsDetail);
        return retAts;
    }

    //190802 B2eTransferOutBank
    public RetAtsSingle B2eTransferOutBank(ReqSingle p_req1908, RetAtsSingle retAts) throws Exception {
        RetAtsSglDetail tmpRetAtsDetail = new RetAtsSglDetail();
        Connection conn = null;
        try {
            TJCB01Header tjcb01Header = new TJCB01Header();
            tjcb01Header.transName = "B2eTransferOutBank";
            tjcb01Header.clientTime = Format.DateTime2Format.format(new Date());
            tjcb01Header.batchID = p_req1908.reqHeader.transSeqID;
            tjcb01Header.transCount = "1";
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeader(xmlWriter, tjcb01Header);
            xmlWriter.writeStartElement("RequestBody");
            XElement requestRecord = new XElement("RequestRecord", "");
            requestRecord.addChild(new XElement("AcctNo", p_req1908.singleDetail.payAct));//付款账号
            requestRecord.addChild(new XElement("PayeeAcctNo", p_req1908.singleDetail.recAct));//收款账号
            requestRecord.addChild(new XElement("PayeeAcctName", p_req1908.singleDetail.recName));//收款户名
            requestRecord.addChild(new XElement("Amount", p_req1908.singleDetail.payAmount));//付款金额
            requestRecord.addChild(new XElement("PayeeBankName", p_req1908.singleDetail.cnapsName));//收款行行名
            requestRecord.addChild(new XElement("PayeeAddress", p_req1908.singleDetail.recBankAddress));//收方行地址
            requestRecord.addChild(new XElement("Note", p_req1908.singleDetail.abstractATS));//存放对账码（明细查询时获取）
            String sendjnlno = DateHelper.convertDateTimetoD8(p_req1908.singleDetail.payDate) + bankFront.org + p_req1908.singleDetail.askNumber;
            requestRecord.addChild(new XElement("Sendjnlno", sendjnlno));
            nodeAnalysis(p_req1908.singleDetail.srcXElement, requestRecord, getCharset());
            xmlWriter.writeXElement(requestRecord);
            xmlWriter.writeEndDocument();

            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            boolean isSendToBank = true;
            try {
                conn = FGBiz.getLocalDbConn();
                int count = JDBCHelper.update(conn, INSERTRECEIPT, new Object[]{uuid, p_req1908.reqHeader.bankCode, p_req1908.singleDetail.askNumber, sendjnlno, DateHelper.convertDateTimetoD8(p_req1908.singleDetail.payDate)});
                if (count < 1) {
                    isSendToBank = false;
                }
            } catch (Exception e) {
                isSendToBank = false;
            } finally {
                if (conn != null) {
                    conn.close();
                }
                if (!isSendToBank) {
                    tmpRetAtsDetail.respCode = "0";
                    tmpRetAtsDetail.respInfo = "发送前流水号落库失败，未发送支付请求，请跟银行确认结果后手工处理";
                    tmpRetAtsDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                    retAts.writeRetDetail(tmpRetAtsDetail);
                    return retAts;
                }
            }

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), p_req1908.reqHeader.transType, p_req1908.reqHeader.commandCode);

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRespCode = tmpBkReader.getFirstText("/transaction/RespondHeader/respondCode");
                    String tmpRespMsg = tmpBkReader.getFirstText("/transaction/RespondHeader/respondInfo");
                    tmpRetAtsDetail.respCode = "0";
                    tmpRetAtsDetail.respInfo = tmpRespMsg;
                    tmpRetAtsDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                    tmpRetAtsDetail.transState = tmpRespCode;
                    tmpRetAtsDetail.payInfoCode = tmpRespCode;
                } else {
                    tmpRetAtsDetail.respCode = "-1";
                    tmpRetAtsDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = tmpStrRet[1];
            }

        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo("单笔跨行转账异常，详情请查看日志！");
            WriteBankLogLn("单笔跨行转账异常:" + e.getMessage());
        }
        retAts.writeRetDetail(tmpRetAtsDetail);
        return retAts;
    }

    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
        //0为跨行 1为同行
        if ("1".equals(p_req1944.sameBnk)) {
            retAts = d_B2eInnerBankStatusQuery(p_req1944, retAts);
        } else {
            retAts = d_B2eOuterBankStatusQuery(p_req1944, retAts);
        }
        return retAts;
    }

    //同行转账结果查询
    public RetAtsSingle d_B2eInnerBankStatusQuery(ReqQrySingle p_req1944, RetAtsSingle retAts) throws Exception {
        RetAtsSglDetail tmpRetAtsDetail = new RetAtsSglDetail();
        Connection conn = null;
        try {
            TJCB01Header tjcb01Header = new TJCB01Header();
            tjcb01Header.transName = "B2eInnerBankStatusQuery";
            tjcb01Header.clientTime = Format.DateTime2Format.format(new Date());
            tjcb01Header.batchID = p_req1944.reqHeader.transSeqID;
            tjcb01Header.transCount = "1";
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeader(xmlWriter, tjcb01Header);
            xmlWriter.writeStartElement("RequestBody");
            xmlWriter.writeStartElement("RequestRecord");
            conn = FGBiz.getLocalDbConn();
            Map<String, Object> map = JDBCHelper.execQuerySingle(conn, SELECTRECEIPT, new Object[]{p_req1944.askNumber, p_req1944.reqHeader.bankCode});
            if (map.size() == 0) {
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = "没有这条请求映射的流水号！";
                retAts.writeRetDetail(tmpRetAtsDetail);
                return retAts;
            }
            xmlWriter.writeElementString("Sendjnlno", map.get("BANKREQSEQID").toString());
            xmlWriter.writeElementString("QueryDate", map.get("TRANSDATE").toString());
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), p_req1944.reqHeader.transType, p_req1944.reqHeader.commandCode);

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmprspcod = tmpBkReader.getFirstText("/transaction/RespondHeader/respondCode");
                    String tmprspmsg = tmpBkReader.getFirstText("/transaction/RespondHeader/respondInfo");
                    if (tmprspcod != null && "0000".equals(tmprspcod)) {
                        tmpRetAtsDetail.respCode = "0";
                        tmpRetAtsDetail.respInfo = tmprspmsg;
                        tmpRetAtsDetail.reqSeqID = p_req1944.askNumber;
                        String tmpTransAmt = tmpBkReader.getFirstTextNotNull("/transaction/RespondBody/RespondRecord/TxAmount");
                        tmpRetAtsDetail.transAmt = StringHelper.isNullOrEmpty(tmpTransAmt) ? "0.00" : tmpTransAmt;
                        tmpRetAtsDetail.transState = tmpBkReader.getFirstTextNotNull("/transaction/RespondBody/RespondRecord/TrsStatus");
                        tmpRetAtsDetail.payInfoCode = tmpRetAtsDetail.transState;
                    } else {
                        tmpRetAtsDetail.respCode = "0";
                        tmpRetAtsDetail.respInfo = tmprspmsg;
                        tmpRetAtsDetail.reqSeqID = p_req1944.askNumber;
                        tmpRetAtsDetail.transState = tmprspcod;
                        tmpRetAtsDetail.payInfoCode = tmpRetAtsDetail.transState;
                    }
                } else {
                    tmpRetAtsDetail.respCode = "-1";
                    tmpRetAtsDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            tmpRetAtsDetail.respCode = "-1";
            tmpRetAtsDetail.respInfo = "同行转账结果查询出现异常，详情查看DSP日志";
            WriteBankLogLn("同行转账结果查询出现异常:" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        retAts.writeRetDetail(tmpRetAtsDetail);
        return retAts;
    }

    //跨行转账结果查询
    public RetAtsSingle d_B2eOuterBankStatusQuery(ReqQrySingle p_req1944, RetAtsSingle retAts) throws Exception {
        RetAtsSglDetail tmpRetAtsDetail = new RetAtsSglDetail();
        Connection conn = null;
        try {
            TJCB01Header tjcb01Header = new TJCB01Header();
            tjcb01Header.transName = "B2eOuterBankStatusQuery";
            tjcb01Header.clientTime = Format.DateTime2Format.format(new Date());
            tjcb01Header.batchID = p_req1944.reqHeader.transSeqID;
            tjcb01Header.transCount = "1";
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeader(xmlWriter, tjcb01Header);
            xmlWriter.writeStartElement("RequestBody");
            xmlWriter.writeStartElement("RequestRecord");
            conn = FGBiz.getLocalDbConn();
            Map<String, Object> map = JDBCHelper.execQuerySingle(conn, SELECTRECEIPT, new Object[]{p_req1944.askNumber, p_req1944.reqHeader.bankCode});
            if (map.size() == 0) {
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = "没有这条请求映射的流水号！";
                retAts.writeRetDetail(tmpRetAtsDetail);
                return retAts;
            }
            xmlWriter.writeElementString("Sendjnlno", map.get("BANKREQSEQID").toString());
            xmlWriter.writeElementString("QueryDate", map.get("TRANSDATE").toString());
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), p_req1944.reqHeader.transType, p_req1944.reqHeader.commandCode);

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmprspcod = tmpBkReader.getFirstText("/transaction/RespondHeader/respondCode");
                    String tmprspmsg = tmpBkReader.getFirstText("/transaction/RespondHeader/respondInfo");
                    if (tmprspcod != null && "0000".equals(tmprspcod)) {
                        tmpRetAtsDetail.respCode = "0";
                        tmpRetAtsDetail.respInfo = tmprspmsg;
                        tmpRetAtsDetail.reqSeqID = p_req1944.askNumber;
                        String tmpTransAmt = tmpBkReader.getFirstTextNotNull("/transaction/RespondBody/RespondRecord/TxAmount");
                        tmpRetAtsDetail.transAmt = StringHelper.isNullOrEmpty(tmpTransAmt) ? "0.00" : tmpTransAmt;
                        tmpRetAtsDetail.transState = tmpBkReader.getFirstText("/transaction/RespondBody/RespondRecord/Status");
                        tmpRetAtsDetail.payInfoCode = tmpRetAtsDetail.transState;
                    } else {
                        tmpRetAtsDetail.respCode = "0";
                        tmpRetAtsDetail.respInfo = tmprspmsg;
                        tmpRetAtsDetail.reqSeqID = p_req1944.askNumber;
                        tmpRetAtsDetail.transState = tmprspcod;
                        tmpRetAtsDetail.payInfoCode = tmpRetAtsDetail.transState;
                    }
                } else {
                    tmpRetAtsDetail.respCode = "-1";
                    tmpRetAtsDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            tmpRetAtsDetail.respCode = "-1";
            tmpRetAtsDetail.respInfo = "跨行转账结果查询出现异常，详情查看日志";
            WriteBankLogLn("跨行转账结果查询出现异常:" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        retAts.writeRetDetail(tmpRetAtsDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
